package main

import (
	"fmt"
	"math/rand"
	"time"
)

/**
*  User: zhanbei
*  Date: 2025/10/27
*  Description: 服务器崩溃动画 - 系统错误、混乱、最终黑屏
 */

// 错误信息列表
var errorMessages = []string{
	"ERROR: Kernel panic - not syncing",
	"FATAL: System halt",
	"ERROR: Memory corruption detected",
	"WARNING: CPU overheating",
	"ERROR: Disk I/O failure",
	"CRITICAL: Database connection lost",
	"ERROR: Segmentation fault (core dumped)",
	"FATAL: Out of memory",
	"ERROR: Network interface down",
	"WARNING: High system load",
	"ERROR: Process killed by signal 9",
	"CRITICAL: File system read-only",
	"ERROR: Unable to mount /dev/sda1",
	"FATAL: Stack overflow detected",
	"ERROR: Null pointer exception",
	"WARNING: Temperature critical",
	"ERROR: Service unavailable",
	"CRITICAL: Security breach detected",
	"ERROR: Authentication failed",
	"FATAL: System resources exhausted",
}

// 系统日志前缀
var logPrefixes = []string{
	"[  ERR ]",
	"[ CRIT ]",
	"[ FAIL ]",
	"[ WARN ]",
	"[ FATAL]",
}

// RunCrash 服务器崩溃动画
func RunCrash() {
	rand.Seed(time.Now().UnixNano())
	width, height := getTerminalSize()

	// 隐藏光标
	hideCursor()
	defer showCursor()

	// 清屏
	clearScreen()

	// 第一阶段：显示正常的服务器信息
	moveCursor(width/2-15, height/2-3)
	setColor(92) // 绿色
	fmt.Print("╔═══════════════════════════╗")
	moveCursor(width/2-15, height/2-2)
	fmt.Print("║   SERVER STATUS: NORMAL   ║")
	moveCursor(width/2-15, height/2-1)
	fmt.Print("║   Uptime: 365 days        ║")
	moveCursor(width/2-15, height/2)
	fmt.Print("║   Load: 0.5 0.3 0.2       ║")
	moveCursor(width/2-15, height/2+1)
	fmt.Print("╚═══════════════════════════╝")
	resetColor()

	time.Sleep(2 * time.Second)

	// 第二阶段：开始出现警告
	clearScreen()
	moveCursor(width/2-10, 3)
	setColor(93) // 黄色
	fmt.Print("⚠  WARNING DETECTED  ⚠")
	resetColor()

	currentLine := 5
	for i := 0; i < 5; i++ {
		moveCursor(5, currentLine)
		setColor(93)
		fmt.Printf("%s %s", logPrefixes[rand.Intn(len(logPrefixes))], errorMessages[rand.Intn(len(errorMessages))])
		resetColor()
		currentLine++
		time.Sleep(300 * time.Millisecond)
	}

	time.Sleep(1 * time.Second)

	// 第三阶段：系统开始崩溃 - 错误信息疯狂刷屏
	moveCursor(width/2-15, currentLine+2)
	setColor(91) // 红色
	fmt.Print("╔═══════════════════════════════╗")
	moveCursor(width/2-15, currentLine+3)
	fmt.Print("║  🔥 SYSTEM FAILURE! 🔥        ║")
	moveCursor(width/2-15, currentLine+4)
	fmt.Print("╚═══════════════════════════════╝")
	resetColor()

	time.Sleep(1 * time.Second)

	// 错误信息快速滚动
	clearScreen()
	scrollLines := 50
	for i := 0; i < scrollLines; i++ {
		row := (i % (height - 3)) + 3
		moveCursor(1, row)

		// 随机颜色（红色系）
		colors := []int{91, 31, 31, 91, 31}
		setColor(colors[rand.Intn(len(colors))])

		prefix := logPrefixes[rand.Intn(len(logPrefixes))]
		msg := errorMessages[rand.Intn(len(errorMessages))]
		fmt.Printf("%s %s", prefix, msg)
		resetColor()

		time.Sleep(50 * time.Millisecond)
	}

	time.Sleep(500 * time.Millisecond)

	// 第四阶段：屏幕混乱 - 随机字符闪烁
	moveCursor(width/2-10, 1)
	setColor(91)
	fmt.Print("⚠ CRITICAL ERROR ⚠")
	resetColor()

	chars := []string{"#", "@", "$", "%", "&", "*", "!", "?", "█", "▓", "▒", "░", "0", "1"}

	for frame := 0; frame < 30; frame++ {
		// 随机位置显示混乱字符
		for i := 0; i < 100; i++ {
			x := rand.Intn(width-1) + 1
			y := rand.Intn(height-3) + 3
			moveCursor(x, y)

			// 随机颜色
			colors := []int{91, 93, 97, 31, 33, 37}
			setColor(colors[rand.Intn(len(colors))])
			fmt.Print(chars[rand.Intn(len(chars))])
		}
		resetColor()
		time.Sleep(80 * time.Millisecond)
	}

	time.Sleep(500 * time.Millisecond)

	// 第五阶段：蓝屏死机效果
	clearScreen()
	// 设置蓝色背景
	fmt.Print("\033[44m") // 蓝色背景
	setColor(97)          // 亮白色文字

	// 清空整个屏幕为蓝色
	for i := 1; i <= height; i++ {
		moveCursor(1, i)
		for j := 0; j < width; j++ {
			fmt.Print(" ")
		}
	}

	// 绘制蓝屏内容
	moveCursor(width/2-25, height/2-5)
	fmt.Print("A problem has been detected and the system has been")
	moveCursor(width/2-25, height/2-4)
	fmt.Print("shut down to prevent damage to your server.")

	moveCursor(width/2-25, height/2-2)
	fmt.Print("CRITICAL_PROCESS_DIED")

	moveCursor(width/2-25, height/2)
	fmt.Print("If this is the first time you've seen this error,")
	moveCursor(width/2-25, height/2+1)
	fmt.Print("restart your server. If this screen appears again,")
	moveCursor(width/2-25, height/2+2)
	fmt.Print("contact your system administrator.")

	moveCursor(width/2-25, height/2+4)
	fmt.Print("Technical information:")
	moveCursor(width/2-25, height/2+5)
	fmt.Print("*** STOP: 0x000000F4 (0x00000003, 0x8B0FBDA8, ...")

	resetColor()
	fmt.Print("\033[49m") // 重置背景

	time.Sleep(3 * time.Second)

	// 第六阶段：屏幕闪烁
	for i := 0; i < 5; i++ {
		clearScreen()
		time.Sleep(100 * time.Millisecond)

		// 恢复蓝屏
		fmt.Print("\033[44m")
		setColor(97)
		for j := 1; j <= height; j++ {
			moveCursor(1, j)
			for k := 0; k < width; k++ {
				fmt.Print(" ")
			}
		}
		moveCursor(width/2-15, height/2)
		fmt.Print("System Shutting Down...")
		resetColor()
		fmt.Print("\033[49m")

		time.Sleep(100 * time.Millisecond)
	}

	// 第七阶段：逐渐变暗
	for brightness := 0; brightness < 3; brightness++ {
		clearScreen()
		if brightness == 0 {
			setColor(90) // 深灰
		} else if brightness == 1 {
			setColor(90) // 更深
		}

		moveCursor(width/2-10, height/2)
		fmt.Print("Shutting down...")
		resetColor()
		time.Sleep(500 * time.Millisecond)
	}

	// 第八阶段：最终黑屏
	clearScreen()
	// 显示一个小点表示电源指示灯
	moveCursor(width/2, height/2)
	setColor(90)
	fmt.Print(".")
	resetColor()

	time.Sleep(1 * time.Second)

	// 完全黑屏
	clearScreen()
	moveCursor(1, height)

	time.Sleep(2 * time.Second)

	// 恢复屏幕
	clearScreen()
	moveCursor(width/2-10, height/2)
	setColor(92)
	fmt.Print("Press any key to continue...")
	resetColor()
	moveCursor(1, height)
	time.Sleep(1 * time.Second)
}
